//
//  UserIconViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/4/27.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "UserIconViewController.h"
#import "UIViewController+BackButtonHandler.h"
@interface UserIconViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) UIImageView *iconImgView;
@property (nonatomic, copy) NSString *imageFile;
@property (nonatomic, copy) NSString *imagePath;
@property (nonatomic, strong) UIImage *IconImage;
@end

@implementation UserIconViewController

- (void)uploadImageRequestWithImage:(UIImage *)image {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kUploadImage];
    QZHUploadFormData *uploadData = [[QZHUploadFormData alloc] init];
    uploadData.imageData = UIImagePNGRepresentation(image);
    uploadData.dataType = DataTypePng;
    uploadData.name = @"img";
    uploadData.fileName = @"image.png";
    [NetworkTools UploadRequestWithParams:dict UrlString:urlString uploadParams:uploadData successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            self.imageFile = responseObject[@"data"][@"file"];
            self.imagePath = responseObject[@"data"][@"path"];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageFile = @"";
    [self setUpUI];
    [self setNav];
}

- (void)setUpUI {
    self.view.backgroundColor = [UIColor blackColor];
    UIImageView *iconImgView = [[UIImageView alloc] init];
    [iconImgView sd_setImageWithURL:[NSURL URLWithString:[[LSUserInfoManager sharedManager] currentUserInfo].u_avatar] placeholderImage:kPlACE_ICON];
    self.iconImgView = iconImgView;
    [self.view addSubview:iconImgView];
    [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_centerY).offset(-64);
        make.width.height.mas_equalTo(kSCREEN_WIDTH);
    }];
}

- (void)setNav {
    self.navigationItem.title = @"个人头像";
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.highlighted = NO;
    btn.frame = CGRectMake(0, 0, 44, 44);
    [btn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateHighlighted];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = -13;
    self.navigationItem.leftBarButtonItems = @[space,leftItem];
    UIButton *changeIconBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [changeIconBtn setImage:kSET_IMAGE(@"changeMore") forState:UIControlStateNormal];
    [changeIconBtn addTarget:self action:@selector(ChangeIcon:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:changeIconBtn];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width = -10;
    self.navigationItem.rightBarButtonItems = @[spaceItem,item];
}

- (void)ChangeIcon:(UIButton *)sender {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"选择照片方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }];
    
    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }];
    [alertVc addAction:camera];
    [alertVc addAction:photos];
    [alertVc addAction:cancle];
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark -- 图片选择代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *IconImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.IconImage = IconImage;
    self.iconImgView.image = IconImage;
    [self uploadImageRequestWithImage:IconImage];
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- Back
- (void)backAction:(UIButton *)sender {
    if (self.iconSurce&&self.imageFile.length&&self.imagePath) {
        self.iconSurce(self.imageFile,self.imagePath,self.IconImage);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
